/*
 * Copyright (C) 2006 The Android Open Source Project
 * Copyright (C) 2013 YIXIA.COM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.moco.launcher.fragment;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.moco.launcher.R;
import com.moco.launcher.activity.MainActivity;
import com.moco.launcher.activity.SleepWaitActivity;
import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.moco.launcher.link.LinkManager;
import com.moco.launcher.listener.OnMusicCategorySelectedListener;
import com.moco.launcher.listener.PopWindowStateCallback;
import com.moco.launcher.play.MocoPlayerClient;
import com.oazon.common.Logger;
import com.oazon.common.util.StringUtils;
import com.oazon.common.util.Utils;
import com.oazon.moco.bean.Metadata;
import com.oazon.moco.bean.PlayMode;
import com.oazon.moco.lan.core.http.bean.CurrentPlayMode;
import com.oazon.moco.lan.core.http.bean.DeleteBean;
import com.oazon.moco.lan.core.http.bean.FavoriteBean;
import com.oazon.moco.link.core.LinkEventController;
import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.playlist.PlayListManage;
import com.oazon.moco.playlist.bean.PlayListCurrentMode;

/**
 * A view containing controls for a MediaPlayer. Typically contains the buttons
 * like "Play/Pause" and a progress slider. It takes care of synchronizing the
 * controls with the state of the MediaPlayer.
 * <p/>
 * The way to use this class is to a) instantiate it programatically or b)
 * create it in your xml layout.
 * <p/>
 * a) The MediaController will create a default set of controls and put them in
 * a window floating above your application. Specifically, the controls will
 * float above the view specified with setAnchorView(). By default, the window
 * will disappear if left idle for three seconds and reappear when the user
 * touches the anchor view. To customize the MediaController's style, layout and
 * controls you should extend MediaController and override the {#link
 * {@link #makeControllerView()} method.
 * <p/>
 * b) The MediaController is a FrameLayout, you can put it in your layout xml
 * and get it through {@link #findViewById(int)}.
 * <p/>
 * NOTES: In each way, if you want customize the MediaController, the SeekBar's
 * id must be mediacontroller_progress, the Play/Pause's must be
 * mediacontroller_pause, current time's must be mediacontroller_time_current,
 * total time's must be mediacontroller_time_total, file name's must be
 * mediacontroller_file_name. And your resources must have a pause_button
 * drawable and a play_button drawable.
 * <p/>
 * Functions like show() and hide() have no effect when MediaController is
 * created in an xml layout.
 */
public class MediaControllerPopWindow extends FrameLayout {
	private static final String TAG = "MEDIA_CONTROLLER";
	
	private static final int FADE_OUT = 1;
	private static final int SHOW_PROGRESS = 2;
	
	private OnMusicCategorySelectedListener mListener;
	public MocoPlayerClient mPlayer;
	public Context mContext;
	private PopupWindow mWindow;
	private int mAnimStyle;
	private View mAnchor;
	private View mRoot;
	private SeekBar mProgress;
	private TextView mEndTime, mCurrentTime;
	private TextView mFileName;
	private String mTitle;
	private long mDuration;
	private boolean mShowing;
	private boolean mDragging;
	private boolean mInstantSeeking = false;
	private boolean mFromXml = false;
	private ImageButton mPauseButton;
	private TextView mTextView = null;
	private ImageView mExitView = null;
	public ImageView mSingleLoopView = null;
	private ImageView mSleepView = null;
	private ImageView mPlayNextView = null;
	private ImageView mPlayPrevView = null;
	private ImageView mBatteryChanged = null;
	private ImageView mImgViewFavorite = null;
	private ImageView mImgViewDelete = null;
	private PopWindowStateCallback mPlayStateCallback = null;
	private AudioManager mAudioManager;
    
	private int LOOP_SINGLE=0;
	public int LOOP_NO_SINGLE=-1;
	
	private boolean isFavorite = false;
	private ImageView mImgViewCategoryBack = null;
	private float x = 0,y= 0;
	public MainActivity mainComtext;
	
	/**
	 * 电池电量的接收，目前没有要求显示
	 */
	private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			
			int curPower = -1;
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
				Logger.d(TAG, "ACTION_BATTERY_CHANGED");
				int level = intent.getIntExtra("level", 0);
				int scale = intent.getIntExtra("scale", 100);
				curPower = (level * 100 / scale) / 25;				
			} else if (action.equals("com.moco.battery.change")) {
				int percent = intent.getIntExtra("percent", 0);
				curPower = percent / 25;
			}
			if (curPower < 0)
				return;
			
			int resId = 0;
			switch (curPower) {
			case 0:
				resId = R.drawable.battery0;
				break;
			case 1:
				resId = R.drawable.battery1;
				break;
			case 2:
				resId = R.drawable.battery2;
				break;
			case 3:
				resId = R.drawable.battery3;
				break;
			case 4:
				resId = R.drawable.battery4;					
				break;
			default:
				break;
			}
			
			if(resId != 0)
				mBatteryChanged.setImageBitmap(BitmapFactory.decodeResource(mContext.getResources(),resId));
		}
	};

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			long pos;
			switch (msg.what) {
			case FADE_OUT:
				hide();
				break;
			case SHOW_PROGRESS:
				pos = setProgress();
				if (!mDragging && mShowing) {
					msg = obtainMessage(SHOW_PROGRESS);
					sendMessageDelayed(msg, 1000 - (pos % 1000));
					updatePausePlay();
				}
				break;
			}
		}
	};

	private View.OnClickListener mPauseListener = new View.OnClickListener() {
		public void onClick(View v) {
			doPauseResume();
			show();
		}
	};

	private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
		public void onStartTrackingTouch(SeekBar bar) {
			mDragging = true;
			mHandler.removeMessages(SHOW_PROGRESS);
			if (mInstantSeeking)
				mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
		}

		public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
			if (!fromuser)
				return;

			if (mInstantSeeking && mCurrentTime != null) {
				long p = (mDuration * progress) / 1000;
				String time = StringUtils.generateTime(p);
				mCurrentTime.setText(time);
			}
		}

		public void onStopTrackingTouch(SeekBar bar) {
			long progress = (mDuration * bar.getProgress()) / 1000;
			
			if (!mInstantSeeking)
				mPlayer.seekTo(progress);

			mHandler.removeMessages(SHOW_PROGRESS);
			mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
			mDragging = false;
			mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);

			// 进度改变通知各协议
			LinkManager.getInstance().setProgress(progress);
		}
	};

	public MediaControllerPopWindow(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		mRoot = this;
		mFromXml = true;
		initController(context);
	}

	private BroadcastReceiver playModeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			String playMode = arg1.getStringExtra("playMode");
			clickSingleLoopView(playMode);
		}
	};

	public MediaControllerPopWindow(Context context) {
		super(context);
		
		if (!mFromXml && initController(context))
			initFloatingWindow();
		
		mListener = (OnMusicCategorySelectedListener)context;
		IntentFilter filter = new IntentFilter("com.moco.play.playmode");
		context.registerReceiver(playModeReceiver, filter);
		mainComtext = (MainActivity)context;
	}

	private boolean initController(Context context) {
		mContext = context;
		mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
		return true;
	}

	public void onDestroy() {
		mContext.unregisterReceiver(playModeReceiver);
	}

	@Override
	public void onFinishInflate() {
		if (mRoot != null)
			initControllerView(mRoot);
	}

	private void initFloatingWindow() {
		mWindow = new PopupWindow(mContext);
		mWindow.setFocusable(false);
		mWindow.setBackgroundDrawable(null);
		mWindow.setOutsideTouchable(true);
		mAnimStyle = android.R.style.Animation;
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	public void setWindowLayoutType() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			try {
				// mAnchor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
				Method setWindowLayoutType = PopupWindow.class.getMethod(
						"setWindowLayoutType", new Class[] { int.class });
				setWindowLayoutType.invoke(mWindow, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
			} catch (Exception e) {
				Logger.d(TAG, "setWindowLayoutType" + e);
			}
		}
	}

	/**
	 * Set the view that acts as the anchor for the control view. This can for
	 * example be a VideoView, or your Activity's main view.
	 *
	 * @param view
	 *            The view to which to anchor the controller when it is visible.
	 */
	public void setAnchorView(View view) {
		mAnchor = view;
		
		if (!mFromXml) {
			removeAllViews();
			
			mRoot = makeControllerView();
			mWindow.setContentView(mRoot);
			mWindow.setWidth(LayoutParams.WRAP_CONTENT);
			mWindow.setHeight(LayoutParams.WRAP_CONTENT);
		}
		
		initControllerView(mRoot);
	}

	/**
	 * Create the view that holds the widgets that control playback. Derived
	 * classes can override this to create their own.
	 *
	 * @return The controller view.
	 */
	protected View makeControllerView() {
		LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		int identifier = getResources().getIdentifier("playcontrol_layout", "layout", mContext.getPackageName());
		return inflater.inflate(identifier, this);
	}

	@SuppressLint("SimpleDateFormat")
	public String getCurrentTime() {
		Calendar c = Calendar.getInstance();
		Logger.d(TAG, "Current time => " + c.getTime());

		SimpleDateFormat df = new SimpleDateFormat("HH:mm");
		String formattedDate = df.format(new Date());
		return formattedDate;
	}

	private void clickSingleLoopView(String playMode) {
		Logger.d(TAG, "mSingleLoopView.callOnClick");
		if (mSingleLoopView == null) 
			return;
		
		final SharedPreferences mConfig = mContext.getSharedPreferences(Utils.CONFIG_FILE, mContext.MODE_PRIVATE);
		final String mode = "single_loop";
		final boolean value = !PlayMode.SINGLE.equals(playMode);
		Logger.d(TAG, "value " + value);

		int resId = 0;
		if (value) {
			mPlayer.setLoopMode(LOOP_NO_SINGLE);
			resId = mContext.getResources().getIdentifier("loop_dark", "drawable",mContext.getPackageName());
		} else {
			mPlayer.setLoopMode(LOOP_SINGLE);
			resId = mContext.getResources().getIdentifier("loop_light", "drawable",mContext.getPackageName());
		}
		
		Editor edit = mConfig.edit();
		edit.putBoolean(mode, !value);
		edit.commit();
		
		if(resId == 0)
			return;
		mSingleLoopView.setImageResource(resId);
	}

	private void initControllerView(View v) {
		String packName = mContext.getPackageName();
		
		mTextView = (TextView)v.findViewById(getResources().getIdentifier("time", "id", packName));
		mExitView = (ImageView)v.findViewById(getResources().getIdentifier("playcontrol_exit", "id",packName));
		mBatteryChanged = (ImageView)v.findViewById(getResources().getIdentifier("battery", "id", packName));
		mSingleLoopView = (ImageView)v.findViewById(getResources().getIdentifier("single_loop", "id", packName));
		mSleepView = (ImageView)v.findViewById(getResources().getIdentifier("sleep_wait", "id", packName));
		mPlayPrevView = (ImageView)v.findViewById(getResources().getIdentifier("prev", "id", packName));
		mPlayNextView = (ImageView)v.findViewById(getResources().getIdentifier("next", "id", packName));
		mPauseButton = (ImageButton)v.findViewById(getResources().getIdentifier("mediacontroller_play_pause", "id", packName));
		mProgress = (SeekBar)v.findViewById(getResources().getIdentifier("mediacontroller_seekbar", "id", packName));
		mEndTime = (TextView)v.findViewById(getResources().getIdentifier("mediacontroller_time_total", "id", packName));
		mCurrentTime = (TextView) v.findViewById(getResources().getIdentifier("mediacontroller_time_current", "id", packName));
		mFileName = (TextView) v.findViewById(getResources().getIdentifier("mediacontroller_file_name", "id", packName));
		mImgViewFavorite = (ImageView)v.findViewById(getResources().getIdentifier("favorite", "id", packName));
		mImgViewDelete = (ImageView)v.findViewById(getResources().getIdentifier("delete", "id", packName));
		mImgViewCategoryBack = (ImageView)v.findViewById(getResources().getIdentifier("category_back", "id",packName));
		
		mExitView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.d(TAG, "onClick..........");
				hide();
			}
		});

		mSingleLoopView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final SharedPreferences mConfig = mContext
						.getSharedPreferences(Utils.CONFIG_FILE, mContext.MODE_PRIVATE);
				final String mode = "single_loop";
				final boolean value = mConfig.getBoolean(mode, false);
				Logger.d(TAG, "single_loop——value: " + value);

				Editor edit = mConfig.edit();
				edit.putBoolean(mode, !value);
				edit.commit();
				
				int resId = 0;
				CurrentPlayMode playMode;
				if (value) {
					mPlayer.setLoopMode(-1);
					resId = mContext.getResources().getIdentifier("loop_dark", "drawable", mContext.getPackageName());
					playMode = CurrentPlayMode.REPEAT_ALL;
				} else {
					mPlayer.setLoopMode(0);
					resId = mContext.getResources().getIdentifier("loop_light", "drawable",mContext.getPackageName());
					playMode =CurrentPlayMode.REPEAT_SINGLE;
				}
				LinkManager.getInstance().setPlayMode(playMode);
				
				if (resId == 0)
					return;
				mSingleLoopView.setImageResource(resId);
			}
		});

		mSleepView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, SleepWaitActivity.class);
				mContext.startActivity(intent);
			}
		});

		mPlayPrevView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mainComtext.switchEnable();
				mPlayer.playPrev();
				hide();
			}
		});

		mPlayNextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mainComtext.switchEnable();
				mPlayer.playNext();
				hide();
			}
		});

		if (mPauseButton != null) {
			mPauseButton.requestFocus();
			mPauseButton.setOnClickListener(mPauseListener);
		}

		if (mProgress != null) {
			if (mProgress instanceof SeekBar) {
				SeekBar seeker = (SeekBar) mProgress;
				seeker.setOnSeekBarChangeListener(mSeekListener);
			}
			mProgress.setMax(1000);
		}

		if (mFileName != null)
			mFileName.setText(mTitle);

		mImgViewFavorite.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!Utils.isWifiConnected(mainComtext)) {
					Toast.makeText(mContext, "网络未连接，无法收藏", Toast.LENGTH_SHORT).show();
					return;
				}
				
				PlayListManage playList = PlayListManage.getInstance();
				
				String songprovider = "";
				if(playList.getCurrentMedia() != null) {
					songprovider = playList.getCurrentMedia().getServiceID();
				}

				
				if (songprovider == null || 
					songprovider.equals(MOCO_CONSTANTS.RECOMMEND_ROOT)) {
					songprovider = "";
				}
				if(playList.getCurrentMedia() == null){
					Toast.makeText(mContext, "未发现播放歌曲", Toast.LENGTH_SHORT).show();
					return;
				}
				setFavorite(!isFavorite);
				mPlayStateCallback.favorite(isFavorite);
			
			}
		});

		mImgViewDelete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if(!Utils.isWifiConnected(mainComtext)){

					Toast.makeText(mContext, "网络未连接，无法删除", Toast.LENGTH_SHORT).show();
					return;
				}
				
				Toast.makeText(mContext, "删除", Toast.LENGTH_SHORT).show();
				mPlayStateCallback.delete();	
				Metadata metadata = PlayListManage.getInstance().getCurrentMedia();
				if(metadata == null){
					return;
				}
				DeleteBean deleteBean = new DeleteBean();
				deleteBean.setCurrentItemID(metadata.getItemID());
				deleteBean.setDelete(true);
				deleteBean.setProvider(metadata.getServiceID());
				LinkSDK.getInstance().delete(LinkEventController.uiSource, deleteBean);
			}
		});
		
		/*增加滑动事件使MediaControllerPopWindow消失
		*/
		mImgViewCategoryBack.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				Logger.d("WGZ", "EVENT==" + event.getAction());
				if (event.getAction() == MotionEvent.ACTION_DOWN ) {
					x = event.getX();
					y = event.getY();
					Logger.d("WGZ","down_X==" + x + "y==" + y);
				}
				
				if(event.getAction() == MotionEvent.ACTION_MOVE) {
					Logger.i("WGZ","X==" + event.getX() + "y==" + event.getY());
					if(Math.abs(event.getX() - x) > 40 || Math.abs(event.getY() - y) > 40){
						Logger.d("WGZ","滑动取消Popwindow");
						hide();
					}
				}
				
				if(event.getAction() == MotionEvent.ACTION_UP)
					Logger.d("WGZ","Up_X==" + event.getX() + "y==" + event.getY());

				return true;
			}
		});
	
	}

	public void setFavorite(boolean isFavorate) {
		this.isFavorite = isFavorate;
		mImgViewFavorite.setImageResource(isFavorate ? R.drawable.favorite2 : R.drawable.favorite1);
	}

	public void setStateCallback(PopWindowStateCallback cb) {
		mPlayStateCallback = cb;
	}

	public void setMediaPlayer(MocoPlayerClient player) {
		mPlayer = player;
		updatePausePlay();
	}

	/**
	 * Control the action when the seekbar dragged by user
	 *
	 * @param seekWhenDragging
	 *            True the media will seek periodically
	 */
	public void setInstantSeeking(boolean seekWhenDragging) {
		mInstantSeeking = seekWhenDragging;
	}

	/**
	 * Set the content of the file_name TextView
	 *
	 * @param name
	 */
	public void setFileName(String name) {
		mTitle = name;
		
		if (mFileName == null)
			return;
			
		mFileName.setText(mTitle);
	}

	/**
	 * <p>
	 * Change the animation style resource for this controller.
	 * </p>
	 * <p/>
	 * <p>
	 * If the controller is showing, calling this method will take effect only
	 * the next time the controller is shown.
	 * </p>
	 *
	 * @param animationStyle
	 *            animation style to use when the controller appears and
	 *            disappears. Set to -1 for the default animation, 0 for no
	 *            animation, or a resource identifier for an explicit animation.
	 */
	public void setAnimationStyle(int animationStyle) {
		mAnimStyle = animationStyle;
	}

	/**
	 * Show the controller on screen. It will go away automatically after
	 * 'timeout' milliseconds of inactivity.
	 *
	 * @param timeout
	 *            The timeout in milliseconds. Use 0 to show the controller
	 *            until hide() is called.
	 */
	public void show() {
		if (!mShowing && mAnchor != null && mAnchor.getWindowToken() != null) {
			if (mPauseButton != null)
				mPauseButton.requestFocus();

			if (mFromXml) {
				Logger.d(TAG, "mFromXml=" + mFromXml);
				setVisibility(View.VISIBLE);
			} else {
				Logger.d(TAG, "NOT mFromXml=" + mFromXml);
				int[] location = new int[2];
				mAnchor.getLocationOnScreen(location);
				Rect anchorRect = new Rect(location[0], location[1],
						location[0] + mAnchor.getWidth(), location[1]
								+ mAnchor.getHeight());

				mWindow.setAnimationStyle(mAnimStyle);
				setWindowLayoutType();
				Logger.d(TAG, "LEFT=" + anchorRect.left + "RIGHT= "
						+ anchorRect.top);
				mWindow.showAtLocation(mAnchor, Gravity.BOTTOM, 0,
						Utils.dip2px(mContext, 10));
			}
			mShowing = true;
			final IntentFilter battery = new IntentFilter();
			battery.addAction(Intent.ACTION_BATTERY_CHANGED);
			battery.addAction("com.moco.battery.change");
			mContext.registerReceiver(mBatteryInfoReceiver, battery);
		}
		updatePausePlay();
		updateFavorite();
		mHandler.sendEmptyMessage(SHOW_PROGRESS);
	}

	public void updateFavorite() {
		try {
			if (PlayListManage.getInstance().getCurrentMedia().isFavorite())
				isFavorite = true;
			else
				isFavorite = false;

			mImgViewFavorite.setImageResource(isFavorite ? R.drawable.favorite2 : R.drawable.favorite1);

		} catch (Exception e) {			
		}
	}

	public boolean isShowing() {
		return mShowing;
	}

	public void hide() {
		if (mAnchor == null)
			return;

		if (!mShowing) 
			return;
		
		try {
			mHandler.removeMessages(SHOW_PROGRESS);
			if (mFromXml)
				setVisibility(View.GONE);
			else
				mWindow.dismiss();
		} catch (IllegalArgumentException ex) {
			Logger.d(TAG, "MediaController already removed");
		}
		mShowing = false;
		mContext.unregisterReceiver(mBatteryInfoReceiver);
	}

	private long setProgress() {
		if (mPlayer == null || mDragging)
			return 0;

		long position = mPlayer.getCurrentPosition();
		long duration = mPlayer.getDuration();
		if (mProgress != null && duration > 0 && position >= 0) {
			long pos = 1000L * position / duration;
			mProgress.setProgress((int) pos);
		}
		
		if(position == -1)
			position = 0;
		
		mDuration = duration;
		if (mEndTime != null)
			mEndTime.setText(StringUtils.generateTime(mDuration));
		
		if (mCurrentTime != null)
			mCurrentTime.setText(StringUtils.generateTime(position));
		if (mTextView != null)
			mTextView.setText(getCurrentTime());

		LinkManager.getInstance().saveProgress(position);
		return position;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		show();
		return true;
	}

	@Override
	public boolean onTrackballEvent(MotionEvent ev) {
		show();
		return false;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (event.getRepeatCount() == 0 && 
				(keyCode == KeyEvent.KEYCODE_HEADSETHOOK || 
				 keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || 
				 keyCode == KeyEvent.KEYCODE_SPACE)) {
			doPauseResume();
			show();
			if (mPauseButton != null)
				mPauseButton.requestFocus();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
			if (mPlayer.isPlaying()) {
				mPlayer.pause();
				updatePausePlay();
			}
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK
				|| keyCode == KeyEvent.KEYCODE_MENU) {
			hide();
			return true;
		} else {
			show();
		}
		
		return super.dispatchKeyEvent(event);
	}

	private void updatePausePlay() {
		if (mRoot == null || mPauseButton == null)
			return;

		final SharedPreferences mConfig = mContext.getSharedPreferences(
				Utils.CONFIG_FILE, mContext.MODE_PRIVATE);
		final String mode = "single_loop";
		final boolean value = mConfig.getBoolean(mode, false);
		Logger.d(TAG, "value " + value);
		
		String packName = mContext.getPackageName();
		String name = null;
		if (value)
			name = "loop_light";
		else
			name = "loop_dark";
		mSingleLoopView.setImageResource(this.getResources().getIdentifier(name, "drawable", packName));

		if (mPlayer.isPlaying()) 
			name = "mediacontroller_pause";
		else 
			name = "mediacontroller_play";
		mPauseButton.setImageResource(getResources().getIdentifier("mediacontroller_pause", "drawable", packName));
	}

	private void doPauseResume() {
		if (mPlayer.isPlaying()) {
			if (mPlayStateCallback != null)
				mPlayStateCallback.pause();
			mPlayer.pause();
		} else {
			mPlayer.start();
			if (mPlayStateCallback != null)
				mPlayStateCallback.play();
		}
		updatePausePlay();
	}

	@Override
	public void setEnabled(boolean enabled) {
		if (mPauseButton != null)
			mPauseButton.setEnabled(enabled);
		if (mProgress != null)
			mProgress.setEnabled(enabled);
		
		super.setEnabled(enabled);
	}
}
